package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.handler.ShoppingCarHandler;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.YgCouponService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.YgShoppingCarService;
import com.ygqh.baby.service.YgSkuService;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 优惠卷
 *
 * @author guohao
 */
@Controller
@RequestMapping("/app/coupon")
public class YgCouponController extends BaseController {

    @Autowired
    private YgCouponService couponService;
    @Autowired
    private YgOrderService orderService;
    @Autowired
    private YgShoppingCarService ygShoppingCarService;
    @Autowired
    private YgSkuService skuService;
    @Autowired
    private ShoppingCarHandler shoppingCarHandler;

    /**
     * 获取优惠卷 及满减金额，运费的接口
     *
     * @param couponDetailId 优惠券明细id
     * @param formId         formId
     * @return
     */
    @RequestMapping(value = "findCouponForPay")
    @ResponseBody
    public ResponseEntity findCouponForPay(Long couponDetailId, String formId) {
        if (couponDetailId == -1L) {
            couponDetailId = null;
        }
        YgUser currentUser = SessionUtil.getCurrentUser();
        List<YgShoppingCarModel> carModelList = ygShoppingCarService.findIsCheck(currentUser.getId(), false,
                SALES_PLATFORM);
        CarPricesResult carPrices = shoppingCarHandler.getCarPrices(carModelList, formId, couponDetailId, SALES_PLATFORM);
        return ResponseEntity.success(carPrices);
    }

    /**
     * 结算页 获取优惠卷列表
     *
     * @param cStatus    优惠券状态
     * @param skuInfos   skuInfos
     * @param formId     formId
     * @param payFromCar 是否为购物车结算
     * @return
     */
    @SuppressWarnings({"unchecked"})
    @RequestMapping(value = "findCouponListForPay", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity findCouponListForPay(@RequestParam CouponStatus cStatus, String skuInfos, String formId,
                                               Boolean payFromCar) {
        YgUser user = SessionUtil.getCurrentUser();
        List<YgShoppingCarModel> carList;
        if (payFromCar != null && payFromCar) {
            // 直接选择商品结算
            carList = getCarList(skuInfos, user.getId());
        } else { // 购物车结算商品
            carList = ygShoppingCarService.findIsCheck(user.getId(), false, SALES_PLATFORM);
        }
        CarPricesResult carPrices = shoppingCarHandler.getCarPrices(carList, formId, null, SALES_PLATFORM);
        ResponseEntity response;
        if (!carPrices.getUseCoupon() && cStatus.equals(CouponStatus.Usable)) {
            response = ResponseEntity.success(null);
        } else {
            BigDecimal couponValidPrice = carPrices.getProductPrice().subtract(carPrices.getNewCustomDisPrice())
                    .subtract(carPrices.getPackDisPrice()).subtract(carPrices.getManJianPrice())
                    .subtract(carPrices.getSpecialPrice());
            if (couponValidPrice.compareTo(new BigDecimal(0)) < 0) {
                couponValidPrice = BigDecimal.ZERO;
            }
            logger.info("findCouponListForPay.CarPricesResult = 【{}】",JSON.toJSONString(carPrices));
            Boolean onlySpecial = false;
            if (couponValidPrice.compareTo(BigDecimal.ZERO) <= 0) {
                onlySpecial = true;
            }
            if (onlySpecial && cStatus.equals(CouponStatus.Usable)) {
                response = ResponseEntity.success(null);
            } else {
                List<YgCouponModel> model = couponService.findCouponListForPayV2(user.getId(), null,
                        couponValidPrice, cStatus, carPrices.getUseCoupon(), onlySpecial, carList, SALES_PLATFORM);
                response = ResponseEntity.success(model);
            }
        }
        return response;
    }

    private List<YgShoppingCarModel> getCarList(String skuInfos, Long userId) {
        List<BaseSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<BaseSkuInfo>>() {
        });
        return ygShoppingCarService.findItemInfo(skuList, userId, PromotionType.Ordinary, false,
                SALES_PLATFORM);
    }

    /**
     * 个人中心获取优惠卷列表
     *
     * @param queryInfo 分页
     * @param cStatus   优惠券状态
     * @param sceneType 作用域
     * @return
     */
    @RequestMapping(value = "findOwnCouponList")
    @ResponseBody
    public ResponseEntity findOwnCouponList(QueryInfo queryInfo, CouponStatus cStatus, SceneType sceneType) {
        YgUser user = SessionUtil.getCurrentUser();
        List<YgCouponModel> couponList = couponService.findOwnCouponList(queryInfo, user.getId(), cStatus, sceneType,
                SALES_PLATFORM);
        return ResponseEntity.success(couponList);
    }

    /**
     * 绑定优惠卷
     *
     * @param couponCode
     * @return
     */
    @RequestMapping(value = "bindCoupon")
    @ResponseBody
    public ResponseEntity bindCoupon(String couponCode) {
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = couponService.bindCoupon(couponCode, user);
        return ResponseEntity.converter(msg);
    }

    /**
     * 领取优惠卷
     *
     * @param couponBatchId 优惠券明细id
     * @return
     */
    @RequestMapping(value = "receiveCoupon")
    @ResponseBody
    public ResponseEntity receiveCoupon(@RequestParam Long couponBatchId) {
        if (couponBatchId == 377) {
            couponBatchId = 411L;
        }
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = couponService.receiveCoupon(couponBatchId, user);
        if (Message.isSuccess(msg)) {
            msg.setExtra(null);
        }
        return ResponseEntity.converter(msg);
    }

    /**
     * 领取优惠卷（支持多个）
     *
     * @param couponBatchIds 优惠券明细id集
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "receiveCouponBatch")
    @ResponseBody
    public ResponseEntity receiveCouponBatch(@RequestParam String couponBatchIds) {
        if (StringUtils.isNotBlank(couponBatchIds)) {
            couponBatchIds = couponBatchIds.replaceAll("377", "411");
        }
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = couponService.receiveCouponBatch(couponBatchIds, user);
        if (Message.isSuccess(msg)) {
            msg.setExtra(null);
        }
        return ResponseEntity.converter(msg);
    }

    /**
     * 获取商品优惠券下的商品列表
     *
     * @param id 优惠券id
     * @return
     */
    @RequestMapping(value = "findProductListByCouponId")
    @ResponseBody
    public ResponseEntity findProductListByCouponId(@RequestParam Long id) {
        ResultSet<YgProduct4ListModel> result = couponService.findProductListByCouponId(id, SALES_PLATFORM);
        return ResponseEntity.success(result.getResult());
    }

    /**
     * 获取优惠（立即购买）
     *
     * @param skuInfos 商品SKU信息集
     * @return
     */
    @RequestMapping(value = "findCouponForPayNow", method = RequestMethod.GET)
    public String findCouponForPayNow(String skuInfos) {
        return skuService.checkSkuInfoIsGroup(skuInfos) ? "forward:/app/coupon/findCouponForPayPt.do"
                : "forward:/app/coupon/findCouponWithSkuInfo.do";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "findCouponWithSkuInfo", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity findCouponWithSkuInfo(Long couponDetailId, String formId, String skuInfos) {
        if (couponDetailId == -1L) {
            couponDetailId = null;
        }
        YgUser user = SessionUtil.getCurrentUser();
        List<YgShoppingCarModel> carList = getCarList(skuInfos, user.getId());
        CarPricesResult carPrices = shoppingCarHandler.getCarPrices(carList, formId, couponDetailId, SALES_PLATFORM);
        return ResponseEntity.success(carPrices);
    }

    /**
     * 获取优惠券信息
     *
     * @param couponId 优惠券id
     * @return
     */
    @RequestMapping(value = "findCouponInfoById")
    @ResponseBody
    public ResponseEntity findCouponInfoById(@RequestParam Long couponId) {
        return ResponseEntity.success(couponService.findById(couponId));
    }

    /**
     * 获取优惠卷 及满减金额，运费的接口
     *
     * @param distribution
     * @param skuInfos
     * @param productPrice
     * @param formId
     * @return
     */
    @RequestMapping(value = "findCouponForPayPt", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity findCouponForPayPt(@RequestParam(defaultValue = "false") Boolean distribution, String skuInfos,
                                             BigDecimal productPrice, String formId) {
        YgUser user = SessionUtil.getCurrentUser();
        List<YgPtSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<YgPtSkuInfo>>() {
        });
        Map<String, Object> map = new HashMap<>();
        List<YgShoppingCarModel> carList = ygShoppingCarService.findItemInfoPt(skuList, user.getId(), distribution, SalesPlatform.Yijiadian);
        BigDecimal ptPrice = new BigDecimal("0");// 拼团商品金额
        for (YgShoppingCarModel car : carList) {
            ptPrice = ptPrice.add(car.getRealSalesPrice().multiply(new BigDecimal(car.getQuantity())));
        }
        // 获取满减金额
        BigDecimal realPrice = ptPrice;
        Map<String, Object> manJian = orderService.getManJianPrice(realPrice, formId, user.getId());
        BigDecimal manJianPrice = (BigDecimal) manJian.get("manjianPrice");
        map.put("coupon", null);
        map.put("packDisPrice", new BigDecimal("0.00"));
        map.put("goupDisPrice", productPrice.subtract(ptPrice));
        map.put("newCustomDisPrice", new BigDecimal("0.00"));
        map.put("expressPrice", new BigDecimal("0.00"));
        map.put("manJianPrice", manJianPrice);
        return ResponseEntity.success(map);
    }
}
